<?php
include($_SERVER['DOCUMENT_ROOT'] . "/admin/includes/interceptor.php");
require_once $_SERVER['DOCUMENT_ROOT'] . '/autoload.php';

use Qiniu\Auth;
use Qiniu\Storage\BucketManager;

// http://developer.qiniu.com/docs/v6/api/reference/rs/list.html#list-description

$accessKey = 'Vr2infZAJEsN8MVWW-KRaFDtyvKbW7YEPIOcudlL';
$secretKey = '-k0wf3uG7kyQIeyRm0OD0VSC3WUK-upZtk7U59tu';
$bucket = 'softwarebox';
$auth = new Auth($accessKey, $secretKey);
$bucketManager = new BucketManager($auth);


// 要列取文件的公共前缀
$prefix = 'software/';
// 上次列举返回的位置标记，作为本次列举的起点信息。
$marker = '';
// 本次列举的条目数
$limit = 200;

$delimiter = '/';


@$in_prefix = $_GET['prefix'];
if ($in_prefix != '') {
    $prefix = $in_prefix;
}
$rows = array();
$options = array();

// 列举文件
do {
    list($ret, $err) = $bucketManager->listFiles($bucket, $prefix, $marker, $limit, $delimiter);
    if ($err !== null) {
        var_dump($err);
    } else {
        $marker = null;
        if (array_key_exists('marker', $ret)) {
            $marker = $ret['marker'];
        }
        //var_dump($ret['items']);
        if (count($ret['items']) > 0) {
            $rows = $ret['items'];
        }
        if (array_key_exists('commonPrefixes', $ret)) {
            $options = $ret['commonPrefixes'];
        }
    }
} while (!empty($marker));
?>
<style>
    .btn-mine {
        background-color: #ffffff;
        border-color: #ffffff;
        color: #000;
    }

    .blockquote-mine {
        padding: 1px 5px;
        margin: 0 0 20px;
        border-left: 5px solid #58c9f3;
    }

    select {
        border: 0;
        outline: none;
    }
</style>
<script>
    var href = "/admin/view/software/softwareUp.php?prefix=<?php echo $prefix?>";

    function showList(obj) {
        href = '/admin/view/software/softwareUp.php?prefix=' + $(obj).val();
        loadMain(href);
    }

    function deleteEntry(key) {
        if (confirm("确定删除吗？")) {
            $.get("/admin/view/software/delete.php", {"key": key}, function (res) {
                loadMain(href);
            });
        }
    }

    function add() {
        // $('#addData').attr("src", "/admin/view/software/addData.php");
        $('#myModal').modal({});
        initUpdate();
    }

    function closeModal() {
        $('#myModal').modal('hide');
        setTimeout(function () {
            loadMain(href);
        }, 100);
    }
</script>
<div class="row">
    <div class="col-lg-12">
        <section class="panel">
            <header class="panel-heading">
                软件列表
                <button type='button' class='btn btn-info btn-mine btn-sm' onclick='add();'><i class='icon-plus'></i>
                </button>
                <?php if (count($options) > 0) { ?>
                    <select onchange="showList(this);" class='btn btn-mine'>
                        <option value="">请选择</option>
                        <?php foreach ($options as $option): ?>
                            <option value="<?php echo $option; ?>">
                                <?php $titles = explode($delimiter, $option);
                                echo $titles[count($titles) - 2] ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                <?php } else { ?>
                    <button class='btn btn-info btn-mine' onclick="showList(this);">返回</button>
                <?php } ?>
            </header>
            <table class="table table-striped table-advance table-hover table-bordered" id="dataTable">
                <thead>
                <tr>
                    <th width="100px" class="hidden-phone">Hash</th>
                    <th><i class="icon-bullhorn"></i> 文件名</th>
                    <th width="260px"><i class="icon-book"></i> 文件类型</th>
                    <th width="100px" class="hidden-phone"><i class="icon-question-sign"></i> 大小</th>
                    <th width="100px" class="hidden-phone"><i class="icon-bookmark"></i> 上传时间</th>
                    <th width="50px">操作</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($rows as $row): ?>
                    <tr>
                        <td class="hidden-phone"><?php echo $row['hash']; ?></td>
                        <td><a href="#"><?php echo $row['key']; ?></a></td>
                        <td><a href="#"><?php echo $row['mimeType']; ?></a></td>
                        <td class="hidden-phone"><?php echo sprintf("%.2f", $row['fsize'] / 1048576) . ' MB'; ?></td>
                        <td class="center hidden-phone"><?php echo date('m-d. Y', $row['putTime'] / 10000000); ?></td>
                        <td>
                            <!--                            <button class="btn btn-primary btn-xs hidden-phone"><i class="icon-pencil"></i></button>-->
                            <button class="btn btn-danger btn-xs" onclick="deleteEntry('<?php echo $row['key'] ?>')"><i
                                        class="icon-trash"></i>
                            </button>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </section>
    </div>
</div>

<!--新增数据弹框-->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    新增数据
                </h4>
            </div>
            <div class="modal-body">
                <blockquote class="blockquote-mine">
                    <h5>上传目录：<?php echo $prefix; ?></h5>
                </blockquote>
                <!--                <iframe id="addData" width="100%" height="715px" frameborder="0" src="/admin/view/software/addData.php?type=1"></iframe>-->
                <label for="file" class="btn btn-primary">选择文件</label>
                <input id="file" type="file" style="display:none"> 上传至：<span id="key">还未选择文件</span>
                <div style="width:100%;text-align:right">
                    <button class="btn btn-danger" id="submit">立即提交</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript" src="/admin/static/assets/data-tables/jquery.dataTables.js"></script>
<script type="text/javascript" src="/admin/static/assets/data-tables/DT_bootstrap.js"></script>
<!---->
<!--<script src="/admin/static/js/dynamic-table.js"></script>-->

<script type="text/javascript" src="https://unpkg.com/qiniu-js@v2/dist/qiniu.min.js"></script>
<script>
    function initUpdate() {
        $.post("/admin/view/software/upToken.php", function (data) {
            var token = data;
            var putExtra = {
                fname: "", // 文件原文件名
                params: {}, // 用来放置自定义变量
                mimeType: null // 用来限制上传文件类型，为 null 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
            };
            var config = {
                useCdnDomain: true,
                region: null // up-z0.qiniup.com 选择上传域名区域；当为 null 或 undefined 时，自动分析上传域名区域
            };
            uploadWithSDK(token, putExtra, config);
        });
    }

    function uploadWithSDK(token, putExtra, config) {
        // 切换tab后进行一些css操作
        $("#file").bind("change", function () {
            var file = this.files[0];
            var observable;
            if (file) {
                var name = file.name;
                putExtra.fname = name;
                var key = '<?php echo $prefix; ?>' + name;
                $("#key").text(key);

                // 设置next,error,complete对应的操作，分别处理相应的进度信息，错误信息，以及完成后的操作
                var error = function (err) {
                    console.log(err);
                    alert("上传出错");
                };

                var complete = function (res) {
                    console.log(res);
                    closeModal();
                };

                var next = function (response) {
                    var total = response.total;
                    console.log("进度：" + total.percent + "% ");
                };

                var subObject = {
                    next: next,
                    error: error,
                    complete: complete
                };
                var subscription;
                // 调用sdk上传接口获得相应的observable，控制上传和暂停
                observable = qiniu.upload(file, key, token, putExtra, config);
                // 开始上传
                $("#submit").click(function () {
                    subscription = observable.subscribe(subObject);
                });
            }
        })
    }

</script>
